<?php
namespace app\wxapi\controller;
use think\Controller;
use app\admin\model\Article as articleModel;//文章模型
use app\admin\model\User as userModel;  //用户模型
use think\Db;
class Wxarticle extends Controller{

		protected $config;
		public function __construct(){	
			$this->config = [
					'appid'=>Db::name('config')->where('field','appid')->cache('appid')->value('value'),
					'appsecret' =>Db::name('config')->where('field','appsecret')->cache('appsecret')->value('value')
			];		
		}

		
		
		//活动显示页面
		public function article_show(){
			return articleModel::where('state',1)->find();
		}

		//活动用户阅读
		public function article_read(){	
			$articleid = input("articleid/d");
			$uid = input("uid/d");
			$page = input('page/d');
			$pagesize = input('pagesize/d')??50;
			//文章阅读人数
			$readUserArr = Db::name('articleview')->field('avatarUrl')->where(['articleid'=>$articleid])->page($page,$pagesize)->select();
			if($uid && $articleid){
			$data = [
				'uid' => $uid,
				'avatarUrl' => input('avatarUrl/s'),
				'articleid' => $articleid,
				'nickName' => input('nickName/s'),
				'time'=>time(),
			];
		
			//用户是否阅读
			$readid = Db::name('articleview')->where(['uid'=>$uid,'articleid'=>$articleid])->value('id');
				if(empty($readid)){
				 	Db::name('articleview')->insert($data);
				 	return json_encode(['code'=>200,'res'=>'阅读成功','data'=>$readUserArr]); 
				}else{
					return json_encode(['code'=>300,'res'=>'该用户已阅读','data'=>$readUserArr]); 
				}
			}else{
				return json_encode(['code'=>500,'res'=>'uid或article不存在','data'=>$readUserArr]); 
			}
		}



		//生成图片
		public function article_Cpic(){	

			$TOKENarr = getToken($this->config['appid'],$this->config['appsecret']);
			$TOKEN = $TOKENarr['access_token'];

			//直接获取菊花图
			$imgeurl = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$TOKEN;
			$postdata = [	
							"line_color"=>['r'=>22,'g'=>48,'b'=>73],
							"width"=>280,
							"path"	=> "pages/index/index?invid=".input('invid/d')
						];
			$imgdata = curl($imgeurl,json_encode($postdata));
			$imageName = "25220_".date("His",time())."_".rand(1111,9999).'.jpg';
			$mumpath = ROOT_PATH .DS."public".DS."uploads".DS. $imageName;
			file_put_contents($mumpath,$imgdata);

			//背景图片
			$path = ROOT_PATH .DS."public".DS."uploads".DS;
			$dsim = imagecreatefromjpeg($path.'bg.jpg');
			//图片尺寸
			$width = imagesx ($dsim); 
    		$height = imagesy ($dsim);

			//文字合成图片昵称
			$namestr = '钟金平--小程序';
			$fontcolor = imagecolorallocate($dsim, 255, 255, 255);
			$nametext = mb_convert_encoding($namestr,"UTF-8" );
			imagettftext($dsim, 30, 0, 220, 1700, $fontcolor, ROOT_PATH .DS."public".DS."msyhbd.ttc", $nametext);


			//获取头像
			$avatarUrl = curl('https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJN14M42iaqF6LSAAdjZwIA3Wc06X5ElvUUgs1IuZsfkekd6SjLehiaP2Os0CNciagehcylWAds4HYxw/132'); //input('avatarUrl/s') 
			$avatarUrlimg = ROOT_PATH .DS."public".DS."uploads".DS. time().'tx.jpg';
			file_put_contents($avatarUrlimg,$avatarUrl);

			//生成头像圆角图片合并背景图
	    	$yjavatarimg = $path. 'yjimg.png';//圆角图片资源
	    	$this->yuan_img($avatarUrlimg,$yjavatarimg);//生成圆角图片
	    	$yjtximg = imagecreatefrompng($yjavatarimg);//($this->img_thumb($yjavatarimg,'png',115));
			imagecopy($dsim,$yjtximg, 60, 1620, 0, 0, imagesx($yjtximg), imagesy($yjtximg));
			
			//菊花图与背景图合成
			$wximg = imagecreatefromjpeg($mumpath);//($this->img_thumb($mumpath,'jpeg',165));
			imagecopy($dsim, $wximg, 710 , 1500, 0, 0, imagesx($wximg), imagesy($wximg));


			//最终海报图片生成
			$imagename = 'ds.jpg';
			$imageaddress = $path.$imagename;
			$dsres = imagejpeg($dsim,$imageaddress);
			if($dsres){	
				unlink($mumpath);
				unlink($avatarUrlimg);
				unlink($yjavatarimg);
				//https://xb.xcx1.top/uploads/bg.jpg
				return json_encode(request()->domain(). DS .'uploads'. DS .$imagename);
			}

		}


		//生成头像图片缩略图
		public 	function img_thumb($imgrooturl,$type="jpeg",$scales=null){
			$scale = $scales??120;	
			
	    	if($type=='jpeg'){
	    		$smallimg = imagecreatefromjpeg($imgrooturl);
		    }elseif($type=='png'){
		    	$smallimg = imagecreatefrompng($imgrooturl);
		    }
	    	$smallw = $smallh = $scale;
			$smallimage = imagecreatetruecolor($smallw,$smallh);//创建120*120像素画布
			imagealphablending($smallimage,false);//这里很重要,意思是不合并颜色,直接用$smallimage图像颜色替换,包括透明色;
    		imagesavealpha($smallimage,true);//这里很重要,意思是不要丢了$smallimage图像的透明色;
			imagecopyresized($smallimage,$smallimg, 0, 0, 0, 0,$smallw,$smallh,imagesx($smallimg),imagesy($smallimg));
			if($type=='jpeg'){
				imagejpeg($smallimage,$imgrooturl);
			}elseif($type=='png'){
				imagepng($smallimage,$imgrooturl);
			}
			imagedestroy($smallimage);	
			return $imgrooturl;
		}
     /*
     * 将正方形头像切成圆角
     */
	public function yuan_img($imgpath,$saveName = ''){
		    $src_img = imagecreatefromstring(file_get_contents($imgpath));
		    $w = imagesx($src_img);$h = imagesy($src_img);
		    $w = $h = min($w, $h);
		    $img = imagecreatetruecolor($w, $h);
		    //这一句一定要有
		    imagesavealpha($img, true);
		    //拾取一个完全透明的颜色,最后一个参数127为全透明
		    $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
		    imagefill($img, 0, 0, $bg);
		    $r   = $w / 2; //圆半径
		    for ($x = 0; $x < $w; $x++) {
		        for ($y = 0; $y < $h; $y++) {
		            $rgbColor = imagecolorat($src_img, $x, $y);
		            if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
		                imagesetpixel($img, $x, $y, $rgbColor);
		            }
		        }
		    }
		    //返回资源
		    if(!$saveName) return $img;
		    //输出图片到文件
		    imagepng ($img,$saveName);
		    //释放空间
		    imagedestroy($src_img);
		    imagedestroy($img);
	}

		//删除活动图片
		public function article_imgdel(){
			if(input('path')){
					$path = ROOT_PATH."public".DS."uploads".DS.input('path/s');
					if(file_exists($path)){
						unlink($path);
						return 200;//菊花图删除成功
					}else{
						echo 'img not exist';
					}
			}else{
				echo 'param not exist';
			}
		}

		

		

}



